const express = require("express");
const router = express.Router();
const moment = require("moment");
const log4js = require("../log-config");
const logger = log4js.getLogger();
const loggererr = log4js.getLogger("err");
const loggeroth = log4js.getLogger("oth");
const loggerinit = log4js.getLogger("init");

// 引用模型
const { User, UserCheckin, UserAddress, Role, Author } = require("../model");

function consolelog(demo) {
  console.log("============================================================");
  try {
    console.log(demo.get({ plain: true }));
  } catch (error) {
    console.log(demo);
  }
  console.log("============================================================");
}

// feed
const userfeed = require("../model/user/feed.json");
const rolefeed = require("../model/role/feed.json");
const authorfeed = require("../model/author/feed.json");
const userAddressfeed = require("../model/userAddress/feed.json");
const userCheckinfeed = require("../model/userCheckin/feed.json");

/* 初始化超级管理员 */
router.post("/root", (req, res, next) => {
  if (req.body.password === "zoneques") {
    Promise.all([
      User.create({
        username: "superadmin",
        password: "123456789",
        mobile: "15994571604",
        email: "15994571604@139.com",
        loginname: "",
        active: true,
        loginTime: "",
        lastTime: ""
      }),
      Role.bulkCreate(rolefeed),
      Author.bulkCreate(authorfeed)
    ])
      .then(function(results) {
        let user = results[0],
          role = results[1],
          author = results[2];
        user.setUserRoles(1);
        role[0].setRoleAuthors(author);
        role[1].setRoleAuthors([
          2,
          3,
          4,
          5,
          6,
          7,
          9,
          10,
          11,
          12,
          13,
          14,
          15,
          16,
          17,
          18,
          19,
          20,
          21,
          22,
          23,
          24
        ]);
        role[2].setRoleAuthors([2, 8]);
        res.set("Content-Type", "application/json; charset=utf-8");
        res.status(200).json({
          message: "初始化成功！",
          user: user,
          role: role,
          author: author
        });
      })
      .catch(next);
  }
});
// 接口文档获取地址
router.get("/", function(req, res, next) {
  res.set("Content-Type", "text/html; charset=utf-8");
  res.status(200).render("apis", {
    title: "权限管理接口文档",
    author: "作者：zes",
    createTime: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
    path: "localhost:3000/apis",
    databasename: "数据库名：stest",
    apis: [
      {
        tableName: "预处理",
        tableHeader: ["name", "api", "params", "way", "tips"],
        tablebody: [
          {
            commit: "初始化",
            api: "/root",
            params: JSON.stringify({
              password: "zoneques"
            }),
            way: "post",
            tips: "需要手动初始化"
          },
          {
            commit: "获得接口处理文档",
            api: "/",
            params: JSON.stringify({}),
            way: "get",
            tips: "暂无，本地浏览器打开: http://localhost:3000/apis/"
          }
        ]
      },
      {
        tableName: "user",
        tableHeader: ["name", "api", "params", "way", "tips"],
        tablebody: [
          {
            commit: "注册新用户",
            api: "/create/user",
            params: JSON.stringify({
              loginname: "zoneques",
              username: "zoneques",
              password: "123456789",
              active: true,
              mobile: "18177189174",
              email: "",
              loginTime: "",
              lastTime: ""
            }),
            way: "post",
            tips: "默认普通用户角色权限。"
          },
          {
            commit: "查询用户（id/mobile）",
            api: "/search/user",
            params: JSON.stringify({
              id: 1,
              mobile: "15994571604"
            }),
            way: "post",
            tips:
              "查询的条件为用户id或者用户注册的mobile。查询失败的原因：1-条件不满足，2-没有初始化，3-确实没有该用户。"
          },
          {
            commit: "查询用户列表（分页）",
            api: "/search/users",
            params: JSON.stringify({
              limit: 10,
              pages: 1,
              demo: "http://localhost:3000/apis/search/users?limit=10&pages=1"
            }),
            way: "get",
            tips: "暂无。"
          },
          {
            commit: "更新用户信息（id）",
            api: "/updata/user/:userId",
            params: JSON.stringify({
              userId: 1
            }),
            way: "put",
            tips: "不支持用户的角色更新。"
          },
          {
            commit: "更新用户角色信息（id）",
            api: "/updata/userRole",
            params: JSON.stringify({
              userId: 1,
              roleId: 1
            }),
            way: "put",
            tips: "用户的角色更新。"
          },
          {
            commit: "删除用户（id/id数组）",
            api: "/delete/user",
            params: JSON.stringify({
              userId: 2
            }),
            way: "delete",
            tips: "用户的角色更新。id为单个number或【number】"
          }
        ]
      },
      {
        tableName: "author",
        tableHeader: ["name", "api", "params", "way", "tips"],
        tablebody: [
          {
            commit: "查询权限列表(分页)",
            api: "/search/authors",
            params: JSON.stringify({
              limit: 10,
              pages: 1,
              demo: "localhost:3000/apis/search/authors?limit=10&pages=1"
            }),
            way: "get",
            tips: "传递的参数为字符串格式，需要转换参数类型，否则查找报错。"
          }
        ]
      },
      {
        tableName: "role",
        tableHeader: ["name", "api", "params", "way", "tips"],
        tablebody: [
          {
            commit: "创建新角色",
            api: "/create/role",
            params: JSON.stringify({
              roleName: "lala",
              description: "description",
              authors: [1, 2, 3, 4, 5, 6, 7]
            }),
            way: "post",
            tips: "创建后，暂时没有设置权限，故查不到最新的角色信息"
          },
          {
            commit: "查询角色列表(分页)",
            api: "/search/roles",
            params: JSON.stringify({
              limit: 10,
              pages: 1,
              demo: "localhost:3000/apis/search/roles?limit=10&pages=1"
            }),
            way: "get",
            tips: "传递的参数为字符串格式，需要转换参数类型，否则查找报错。"
          },
          {
            commit: "查询某个特定角色(id)",
            api: "/search/role/:id",
            params: JSON.stringify({
              id: 1
            }),
            way: "get",
            tips: "暂无"
          },
          {
            commit: "更新角色(id)",
            api: "/updata/role",
            params: JSON.stringify({
              roleId: 1,
              content: {
                roleName: "roleName",
                description: "description"
              },
              authors: ["authorId"]
            }),
            way: "put",
            tips: "更新后，新设定的权限暂时没有查到，故查不到最新的角色信息"
          },
          {
            commit: "更新角色权限(id)",
            api: "/updata/roleAuthor/[roleId]",
            params: JSON.stringify({
              authors: ["authorId"]
            }),
            way: "put",
            tips:
              "更新后，新设定的权限暂时没有查到，故查不到最新的角色信息。仅仅限制于更新角色权限。"
          },
          {
            commit: "删除角色(id)",
            api: "/delete/role/[roleId]",
            params: JSON.stringify({}),
            way: "delete",
            tips: "未校验当有用户使用该角色时的情况。"
          }
        ]
      }
    ]
  });
});
/* 初始化 end */

/*  user */
// 创建新用户
router.post("/create/user", (req, res, next) => {
  User.findOrCreate({
    where: {
      mobile: req.body.mobile
    },
    defaults: req.body
  }).spread((user, created) => {
    res.set("Content-Type", "application/json; charset=utf-8");
    if (created) {
      // 创建成功，数据不存在
      if (user.id != 1) {
        // 1 默认值权限-超级管理员 2-管理员 3-普通用户
        user.setUserRoles(3);
      }
      res.json({
        data: user,
        message: "success"
      });
    } else {
      res.status(501).json({
        data: req.body,
        message: "创建失败，该用户已经创建！"
      });
    }
  });
});
// 查询某个特定用户（id）
router.post("/search/user", (req, res, next) => {
  User.findAll({
    where: {
      $or: [{ id: req.body.id }, { mobile: req.body.mobile }]
    },
    attributes: ["id", "username", "active"],
    include: [
      {
        model: Role,
        as: "UserRoles",
        attributes: ["id", "roleName"],
        include: [
          {
            model: Author,
            as: "RoleAuthors",
            attributes: ["id", "authorName"]
          }
        ]
      }
    ]
  })
    .then(user => {
      res.set("Content-Type", "application/json; charset=utf-8");
      if (user.length) {
        user = user[0];
        res.status(200).end(JSON.stringify({ user, message: "查询成功！" }));
      } else {
        res.status(501).end(JSON.stringify({ message: "查询失败！" }));
      }
    })
    .catch(next);
});
// 查询用户列表
router.get("/search/users", (req, res, next) => {
  let limit = +req.query.limit,
    offset = (req.query.pages - 1) * limit;
  User.findAndCountAll({
    where: {},
    attributes: ["id", "username", "active"],
    // include: [
    //   {
    //     model: Role,
    //     as: "UserRoles",
    //     attributes: ["id", "roleName"],
    //     include: [
    //       {
    //         model: Author,
    //         as: "RoleAuthors",
    //         attributes: ["id", "authorName"]
    //       }
    //     ]
    //   }
    // ],
    limit: limit,
    offset: offset
  })
    .then(result => {
      res.set("Content-Type", "application/json; charset=utf-8");
      res.status(200).end(JSON.stringify(result));
    })
    .catch(next);
});
// 更新某个特定用户（id）
router.put("/updata/user/:userId", (req, res, next) => {
  User.update(req.body.content, {
    where: { id: req.params.userId },
    validate: true
  })
    .then(user => {
      res.set("Content-Type", "application/json; charset=utf-8");
      if (user[0]) {
        res.status(200).end(
          JSON.stringify({
            message: "更新成功！",
            userId: req.params.userId
          })
        );
      } else {
        res.status(501).end(
          JSON.stringify({
            message: "更新失败，没有该用户！",
            userId: req.params.userId
          })
        );
      }
    })
    .catch(next);
});
// 用户角色更新（id）
router.put("/updata/userRole", (req, res, next) => {
  User.findById(req.body.userId)
    .then(user => {
      user.setUserRoles(req.body.roleId);
      res.set("Content-Type", "application/json; charset=utf-8");
      res.status(200).end(
        JSON.stringify({
          message: "用户角色更新成功！",
          userId: req.body.userId
        })
      );
    })
    .catch(next);
});
// 删除某个特定的用户（id/id数组）
router.delete("/delete/user", (req, res, next) => {
  User.destroy({
    where: {
      id: req.body.id
    },
    hooks: true
  })
    .then(result => {
      res.set("Content-Type", "application/json; charset=utf-8");
      res.status(200).end(
        JSON.stringify({
          message: "删除成功！"
        })
      );
    })
    .catch(next);
});
//
/*  user end */

/* role */
// 创建新角色
router.post("/create/role", (req, res, next) => {
  Role.findOrCreate({
    where: {
      roleName: req.body.roleName
    },
    defaults: {
      roleName: req.body.roleName,
      description: req.body.description
    }
  }).spread((role, created) => {
    res.set("Content-Type", "application/json; charset=utf-8");
    if (created) {
      // 创建了，说明之前不存在
      role.setRoleAuthors(req.body.authors);
      res.status(200).end(
        JSON.stringify({
          message: "创建成功！",
          data: role
        })
      );
    } else {
      res.status(501).end(
        JSON.stringify({
          message: "创建失败，该角色已存在！",
          role: []
        })
      );
    }
  });
});
// 查询某个特定的角色（id划分）
router.get("/search/role/:id", (req, res, next) => {
  Role.findById(req.params.id, {
    attributes: ["id", "roleName", "description"],
    include: [
      {
        model: Author,
        as: "RoleAuthors",
        attributes: ["id", "parentTd", "authorName", "description"]
      }
    ]
  })
    .then(result => {
      res.set("Content-Type", "application/json; charset=utf-8");
      res.status(200).end(JSON.stringify(result));
    })
    .catch(next);
});
// 查询所有角色
router.get("/search/roles", (req, res, next) => {
  let limit = +req.query.limit,
    offset = (req.query.pages - 1) * limit;
  Role.findAndCountAll({
    attributes: ["id", "roleName", "description"],
    include: [
      {
        model: Author,
        as: "RoleAuthors",
        attributes: ["id", "parentTd", "authorName", "description"],
        required: true
      }
    ],
    limit: limit,
    offset: offset
  })
    .then(result => {
      res.set("Content-Type", "application/json; charset=utf-8");
      res.status(200).end(JSON.stringify(result));
    })
    .catch(next);
});
// 更新角色信息
router.put("/updata/role", (req, res, next) => {
  Role.update(req.body.content, {
    where: {
      id: req.body.roleId
    },
    validate: true
  })
    .then(result => {
      // role.setRoleAuthors(req.body.authors);
      Role.findById(req.body.roleId, {
        attributes: ["id", "roleName", "description"],
        include: [
          {
            model: Author,
            as: "RoleAuthors",
            attributes: ["id", "parentTd", "authorName", "description"]
          }
        ]
      }).then(role => {
        role.setRoleAuthors(req.body.authors);
      });
      res.set("Content-Type", "application/json; charset=utf-8");
      res.status(200).end(
        JSON.stringify({
          message: "更新成功",
          data: req.body.roleId
        })
      );
    })
    .catch(next);
});
// 更新角色的权限
router.put("/updata/roleAuthor/:roleId", (req, res, next) => {
  Role.findById(req.params.roleId, {
    attributes: ["id", "roleName", "description"],
    include: [
      {
        model: Author,
        as: "RoleAuthors",
        attributes: ["id", "parentTd", "authorName", "description"]
      }
    ]
  })
    .then(role => {
      role.setRoleAuthors(req.body.authors);
      res.set("Content-Type", "application/json; charset=utf-8");
      res.status(200).end(
        JSON.stringify({
          message: "更新成功",
          data: req.body.authors
        })
      );
    })
    .catch(next);
});
// 删除角色
router.delete("/delete/role/:roleId", (req, res, next) => {
  Role.destroy({
    where: {
      id: req.params.roleId
    },
    hooks: true
  })
    .then(result => {
      res.set("Content-Type", "application/json; charset=utf-8");
      res.status(200).end(
        JSON.stringify({
          message: "删除成功！"
        })
      );
    })
    .catch(next);
});
/* role end */

/* author */
// 查询权限列表
router.get("/search/authors", (req, res, next) => {
  let limit = +req.query.limit,
    offset = (req.query.pages - 1) * limit;
  Author.findAndCountAll({
    where: {},
    limit: limit,
    offset: offset
  })
    .then(result => {
      res.set("Content-Type", "application/json; charset=utf-8");
      res.status(200).end(JSON.stringify(result));
    })
    .catch(next);
});
/* author end */

module.exports = router;
